from moviepy.editor import VideoFileClip
from moviepy.config import get_setting
import os,logging,json,requests,subprocess

# 设置MoviePy的日志级别为 "CRITICAL"
logger = logging.getLogger('moviepy')
logger.setLevel(logging.CRITICAL)

# 禁用MoviePy的控制台日志处理器
for handler in logger.handlers:
    if isinstance(handler, logging.StreamHandler):
        logger.removeHandler(handler)

def silent_ffmpeg_extract_subclip(filename, t1, t2, targetname=None):
    """
    重写提取片段的函数，用于隐藏输出框内的日志信息
    """
    cmd = [get_setting("FFMPEG_BINARY"),"-y",
           "-ss", "%0.2f" % t1,
           "-i", filename,
           "-t", "%0.2f" % (t2-t1),
           "-vcodec", "copy", "-acodec", "copy", targetname]
    subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

def splitVideo(video_path):
    # 视频路径
    # video_path = r"D:\python\feiguaSpider\data\20230725\video_5.mp4"

    # 创建VideoFileClip对象
    clip = VideoFileClip(video_path)

    # 获取视频时长（单位：秒）
    duration = clip.duration

    # 将时间转换为秒
    duration_in_sec = int(duration)

    # 若视频长度超过1分钟
    if duration_in_sec > 30:

        data_list = []
        # 将视频按30秒为一个单位划分

        for i in range(0, duration_in_sec, 30):
            if i == 6:
                break
            # 临时文件的名称
            temp_file = f"temp_{i}.mp4"

            # 提取子片段
            silent_ffmpeg_extract_subclip(video_path, i, min(i+20, duration_in_sec), targetname=temp_file)

            # 使用requests库向API发送视频文件
            with open(temp_file, 'rb') as f:
                response = requests.post(url="http://whisper.yeyupiaoling.cn:8081/recognition",
                     files=[("audio", ("test.wav", f, 'audio/wav'))],
                     json={"to_simple": 1, "remove_pun": 0, "language": "zh", "task": "transcribe"},
                     timeout=20)

                data_list.append(response.text)

            # 删除临时文件
            os.remove(temp_file)
        return data_list
    else:
        data_list = []

        with open(video_path, 'rb') as f:
            response = requests.post(url="http://whisper.yeyupiaoling.cn:8081/recognition",
                                     files=[("audio", ("test.wav", f, 'audio/wav'))],
                                     json={"to_simple": 1, "remove_pun": 0, "language": "zh", "task": "transcribe"},
                                     timeout=20)

        data_list.append(response.text)

        return data_list

def dealResult(data_list):
    print('----'*50)
    print(data_list)
    string = ''
    for index, results in enumerate(data_list):
        # data = dict(data)
        data_dict = json.loads(results)

        for data in data_dict['results']:
            result = data['result']
            string += result

    print(string)

if __name__ == '__main__':
    for i in range(0,20):
        path = r"D:\python\feiguaSpider\data\20230726\video{}.mp4".format(i)
        data_list = splitVideo(path)
        dealResult(data_list)